import { ref, computed, readonly } from 'vue';
import { UploadService } from '@/api';
import type { FileInfo, UploadStatistics, ApiResponse } from '@/api';

/**
 * 文件上传状态
 */
export interface UploadState {
  isUploading: boolean;
  progress: number;
  uploadedFiles: FileInfo[];
  error: string | null;
}

/**
 * 文件上传组合式函数
 */
export function useUpload() {
  // 响应式状态
  const uploadState = ref<UploadState>({
    isUploading: false,
    progress: 0,
    uploadedFiles: [],
    error: null,
  });

  // 计算属性
  const hasUploadedFiles = computed(() => uploadState.value.uploadedFiles.length > 0);
  const uploadProgress = computed(() => uploadState.value.progress);
  const isUploading = computed(() => uploadState.value.isUploading);
  const uploadError = computed(() => uploadState.value.error);

  /**
   * 重置上传状态
   */
  const resetUploadState = () => {
    uploadState.value = {
      isUploading: false,
      progress: 0,
      uploadedFiles: [],
      error: null,
    };
  };

  /**
   * 单文件上传
   */
  const uploadSingle = async (file: File, userId?: string): Promise<FileInfo | null> => {
    try {
      uploadState.value.isUploading = true;
      uploadState.value.error = null;
      uploadState.value.progress = 0;

      const result = await UploadService.uploadSingle({ file, userId });

      if (result.success) {
        uploadState.value.uploadedFiles.push(result.data);
        uploadState.value.progress = 100;
        return result.data;
      } else {
        uploadState.value.error = result.message;
        return null;
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '上传失败';
      return null;
    } finally {
      uploadState.value.isUploading = false;
    }
  };

  /**
   * 批量文件上传
   */
  const uploadBatch = async (files: File[], userId?: string): Promise<FileInfo[]> => {
    try {
      uploadState.value.isUploading = true;
      uploadState.value.error = null;
      uploadState.value.progress = 0;

      const result = await UploadService.uploadBatch({ files, userId });

      if (result.success) {
        uploadState.value.uploadedFiles.push(...result.data);
        uploadState.value.progress = 100;
        return result.data;
      } else {
        uploadState.value.error = result.message;
        return [];
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '批量上传失败';
      return [];
    } finally {
      uploadState.value.isUploading = false;
    }
  };

  /**
   * 删除文件
   */
  const deleteFile = async (imageId: number, userId?: string): Promise<boolean> => {
    try {
      const result = await UploadService.deleteFile({ imageId, userId });

      if (result.success) {
        // 从已上传文件列表中移除
        uploadState.value.uploadedFiles = uploadState.value.uploadedFiles.filter(
          file => file.id !== imageId
        );
        return true;
      } else {
        uploadState.value.error = result.message;
        return false;
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '删除失败';
      return false;
    }
  };

  /**
   * 获取文件信息
   */
  const getFileInfo = async (imageId: number, userId?: string): Promise<FileInfo | null> => {
    try {
      const result = await UploadService.getFileInfo({ imageId, userId });

      if (result.success) {
        return result.data;
      } else {
        uploadState.value.error = result.message;
        return null;
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '获取文件信息失败';
      return null;
    }
  };

  /**
   * 获取上传统计信息
   */
  const getUploadStatistics = async (userId?: string): Promise<UploadStatistics | null> => {
    try {
      const result = await UploadService.getUploadStatistics(userId);

      if (result.success) {
        return result.data;
      } else {
        uploadState.value.error = result.message;
        return null;
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '获取统计信息失败';
      return null;
    }
  };

  /**
   * 检查文件是否存在
   */
  const checkFileExists = async (filePath: string): Promise<boolean> => {
    try {
      const result = await UploadService.checkFileExists({ filePath });

      if (result.success) {
        return result.data;
      } else {
        uploadState.value.error = result.message;
        return false;
      }
    } catch (error) {
      uploadState.value.error = error instanceof Error ? error.message : '检查文件存在性失败';
      return false;
    }
  };

  /**
   * 文件类型验证
   */
  const validateFileType = (file: File, allowedTypes: string[]): boolean => {
    const isValid = allowedTypes.includes(file.type);
    if (!isValid) {
      uploadState.value.error = `不支持的文件类型: ${file.type}`;
    }
    return isValid;
  };

  /**
   * 文件大小验证
   */
  const validateFileSize = (file: File, maxSizeMB: number): boolean => {
    const maxSizeBytes = maxSizeMB * 1024 * 1024;
    const isValid = file.size <= maxSizeBytes;
    if (!isValid) {
      uploadState.value.error = `文件大小超过限制: ${(file.size / 1024 / 1024).toFixed(2)}MB > ${maxSizeMB}MB`;
    }
    return isValid;
  };

  /**
   * 清除错误信息
   */
  const clearError = () => {
    uploadState.value.error = null;
  };

  return {
    // 状态
    uploadState: readonly(uploadState),
    hasUploadedFiles,
    uploadProgress,
    isUploading,
    uploadError,

    // 方法
    resetUploadState,
    uploadSingle,
    uploadBatch,
    deleteFile,
    getFileInfo,
    getUploadStatistics,
    checkFileExists,
    validateFileType,
    validateFileSize,
    clearError,
  };
}

/**
 * 文件拖拽上传组合式函数
 */
export function useDragUpload() {
  const isDragOver = ref(false);
  const dragCounter = ref(0);

  const handleDragEnter = (event: DragEvent) => {
    event.preventDefault();
    dragCounter.value++;
    isDragOver.value = true;
  };

  const handleDragLeave = (event: DragEvent) => {
    event.preventDefault();
    dragCounter.value--;
    if (dragCounter.value === 0) {
      isDragOver.value = false;
    }
  };

  const handleDragOver = (event: DragEvent) => {
    event.preventDefault();
  };

  const handleDrop = (event: DragEvent, onFilesDrop: (files: File[]) => void) => {
    event.preventDefault();
    isDragOver.value = false;
    dragCounter.value = 0;

    const files = Array.from(event.dataTransfer?.files || []);
    if (files.length > 0) {
      onFilesDrop(files);
    }
  };

  return {
    isDragOver: readonly(isDragOver),
    handleDragEnter,
    handleDragLeave,
    handleDragOver,
    handleDrop,
  };
} 